/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function (prices) {
  if (prices.length === 0) return 0
  let max = 0 //最大利润
  let low = prices[0] //波谷
  let top = prices[0] //波峰

  let i = 0
  while (i < prices.length - 1) {
    while (i < prices.length - 1 && prices[i] >= prices[i + 1]) i++ //跌的时候i++
    low = prices[i] //获得波谷
    while (i < prices.length - 1 && prices[i] <= prices[i + 1]) i++
    top = prices[i] //获得波峰

    max += top - low //最大利润为波峰减波谷
  }
  return max
};